package titt.io.reader;

import titt.TITTValues;
import titt.head.request.form.FormHead;
import titt.head.request.form.MultipartHead;
import titt.io.IOFactory;
import titt.io.encoding.Decoder;
import titt.io.socket.TITTSocket;
import titt.io.socket.in.StaticInputStream;
import titt.type.Type;
import titt.type.TypedObject;
import titt.util.search.ByteSearch;

public class POSTReader implements Reader<TypedObject> {

	private final FormHead fh;
	private final TITTSocket ts;
	private final Decoder denc;
	
	public POSTReader(TITTSocket ts, Decoder denc, FormHead fh) {
		this.ts = ts;
		this.fh = fh;
		this.denc = denc;
	}	

	@Override
	public TypedObject[] readValues() throws Exception {
		byte[] complete_data = new byte[fh.getContentLength()];
		byte[][] bounds = fh.getBounds();
		
		ts.getInputStream().read(complete_data);
		
		ByteSearch bs = new ByteSearch(complete_data);
				
		byte[][] byte_vals = bs.split(bounds[0]);

		TypedObject[] ots = new TypedObject[byte_vals.length - 2];
		
		for(int i = 0; i < ots.length; i++) {
			StaticInputStream sis = new StaticInputStream(byte_vals[i+1], TITTValues.HTTP_NEWLINE_LENGTH, byte_vals[i+1].length - 2 * TITTValues.HTTP_NEWLINE_LENGTH);

			Type t = new MultipartHead(IOFactory.createHeadReader(sis).readHead(false)).getType();
			
			if(!denc.isDecodeable(t)) 
				ots[i] = new TypedObject(t, null);
			else
				ots[i] = new TypedObject(t, denc.decode(t, sis.readFully()));
		}
		
		return ots;
	}

	
}
